package com.my.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.my.entity.Admin;
import com.my.service.AdminService;
import com.my.util.Rest;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService service;

    @GetMapping("list")
    public String list(Model model, @RequestParam(defaultValue = "1") int pageNo, Admin admin) {
        model.addAttribute("page", service.page(new Page<>(pageNo, 10), new QueryWrapper<Admin>()
                .like(StrUtil.isNotBlank(admin.getUsername()), "username", admin.getUsername())
                .eq(admin.getSex() != null, "sex", admin.getSex())));
        model.addAttribute("username", admin.getUsername());
        model.addAttribute("sex", admin.getSex());
        return "admin/list";
    }

    @GetMapping("edit")
    public String edit(Model model, Long id) {
        if(id != null) {
            model.addAttribute("admin", service.getById(id));
        }
        return "admin/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public Rest edit(Admin admin) {
        if(admin.getId() == null && StrUtil.isBlank(admin.getPassword())) {
            admin.setPassword("123456");
        }
        if(StrUtil.isNotBlank(admin.getPassword())) {
            admin.setPassword(SecureUtil.md5(admin.getUsername() + admin.getPassword()));
        }
        if(admin.getId() == null ? service.save(admin): service.updateById(admin)) {
            return Rest.ok("保存成功！");
        }
        return Rest.err("保存失败！");
    }

    @PostMapping("del")
    @ResponseBody
    public Rest del(Long id) {
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

}
